package org.pearl.validation.demo.controller;

import org.pearl.validation.demo.pojo.Insert;
import org.pearl.validation.demo.lombok.Person;
import org.pearl.validation.demo.pojo.Select;
import org.pearl.validation.demo.pojo.User;
import org.pearl.validation.demo.service.impl.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by TD on 2021/5/14 @Validated
 */
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    TestService testService;

    @GetMapping("/test001")
    public Object test001(@Validated User user) {
        return user;
    }


    @GetMapping("/test002")
    public Object test002(String pwd) {
        User user = new User();
        user.setPassword(pwd);
        testService.testValid(user);
        return user;
    }
/*

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(new PersonValidator());
    }
*/

    @GetMapping("/person")
    public Object person(@Validated Person person, BindingResult result) {
        // 参数校验
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach(e -> {
                System.out.println(e.getField() + e.getCode());
            });
            throw new IllegalArgumentException("参数输入错误");
        }
        return person;
    }


    @GetMapping("/select")
    public Object select(@Validated({Select.class}) Person person) {
        return person;
    }

    @GetMapping("/insert")
    public Object insert(@Validated(Insert.class) Person person) {
        return person;
    }

    @GetMapping("/num")
    public Object num(@Validated Person person) {
        return person;
    }
}
